import React, { Component } from 'react';
import { routerRedux, Route, Switch, Link } from 'dva/router';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button,
  Menu,
  Dropdown,
  Icon,
  Row,
  Col,
  Input,
  InputNumber,
  Steps,
  Card,
  Popover,
  Badge,
  Table,
  Tooltip,
  Divider,
  Checkbox,
  Modal,
  Radio,
  Select,
  message,
  TreeSelect,
  Form,
  Upload,
  Spin,
  DatePicker,
} from 'antd';
import moment from 'moment';
import classNames from 'classnames';
import { getRoutes } from '../../../utils/utils';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import DescriptionList from '../../../components/DescriptionList';
import styles from './style.less';
import { create } from 'domain';
import { solo } from '../../../common/solo';

import querystring from 'querystring';
import Description from '../../../components/Falcon/Description';

import { wrapFileList } from '../../../utils/utils';

const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
const formItemLayout2 = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};
const formItemLayout1 = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 16,
  },
};

const USER_FROM_NEW_ENTER = 1;
const USER_FROM_BACK_FROM_NEXT_STEP = 2;

/**
 * {
 * {
        uid: "rc-upload-1532748449493-11",
        name: "1.jpg",
        status: "done",
        response:{body:{key:'6428813118415044608.jpg'}},
        url: "http://192.168.2.42:9020/files/6428813118415044608.jpg"
      }
 * 
        uid: "rc-upload-1532748449493-11",
        name: "1.jpg",
        status: "done",
        response:{body:{key:'6428813118415044608.jpg'}},
        url: "http://192.168.2.42:9020/files/6428813118415044608.jpg"
      }
 */
@connect(({ channel, system }) => ({
  channel,
  system,
}))
@Form.create()
export default class Step1 extends Component {
  state = {
    type: '',
    dealerLevel: false,
    branchIdList: [],
    channelDetailValue: {},
    agreementFileList: [],
    agreementTypeFileList: [],
    otherFileList: [],
    otherTypeFileList: [],

    imageMap: {
      idImg: [],
      licenseImg: [],
      doorImg: [],
      hallImg: [],
      cardImg: [],
      bankCardImg: [],
    },

    attachmentMap: {
      agreement: [],
      other: [],
    },

    attachmentMapKey: {
      agreement: [],
      other: [],
    },
    isLoaded: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    const userFromType = params.type;

    // dispatch({
    //   type: 'system/fetchBasic',
    // });

    dispatch({
      type: 'system/getBranchTreeList',
    });

    if (userFromType == USER_FROM_NEW_ENTER) {
      this.setState({
        type: userFromType,
        isLoaded: true,
      });
    }

    if (userFromType == USER_FROM_BACK_FROM_NEXT_STEP) {
      const { channel: { channelDetailValue } } = this.props;
      if (channelDetailValue) {
        const { imageMap, attachmentMap } = channelDetailValue;
        this.setState({
          channelDetailValue,
          type: params.type,
          imageMap,
          attachmentMap,
          isLoaded: true,
        });
      }
    }
  }

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '营业执照':
        this.setState({
          imageMap: { ...this.state.imageMap, licenseImg: fileList },
        });
        break;
      case '身份证照':
        this.setState({
          imageMap: { ...this.state.imageMap, idImg: fileList },
        });
        break;
      case '门头照':
        this.setState({
          imageMap: { ...this.state.imageMap, doorImg: fileList },
        });
        break;
      case '展厅照':
        this.setState({
          imageMap: { ...this.state.imageMap, hallImg: fileList },
        });
        break;
      case '名片':
        this.setState({
          imageMap: { ...this.state.imageMap, cardImg: fileList },
        });
        break;
      case '银行卡':
        this.setState({
          imageMap: { ...this.state.imageMap, bankCardImg: fileList },
        });
        break;
    }
  };

  handelNextStep = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    let attachmentMapKey = this.state.attachmentMapKey;
    if (this.state.attachmentMap.agreement.length > 0) {
      for (let i = 0; i < this.state.attachmentMap.agreement.length; i++) {
        attachmentMapKey.agreement.push(this.state.attachmentMap.agreement[i].key);
      }
    }
    if (this.state.attachmentMap.other.length > 0) {
      for (let i = 0; i < this.state.attachmentMap.other.length; i++) {
        attachmentMapKey.other.push(this.state.attachmentMap.other[i].key);
      }
    }
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        if (values.dealerName && values.branchId) {
          const payload = {
            ...values,
            imageMap: this.state.imageMap,
            cooperateProtocol: attachmentMapKey.agreement,
            otherProtocol: attachmentMapKey.other,
            attachmentMap: this.state.attachmentMap,
            bankCardImg:
              this.state.imageMap.bankCardImg[0] && this.state.imageMap.bankCardImg[0].key,
            cardImg: this.state.imageMap.cardImg[0] && this.state.imageMap.cardImg[0].key,
            hallImg: this.state.imageMap.hallImg[0] && this.state.imageMap.hallImg[0].key,
            idImg: this.state.imageMap.idImg[0] && this.state.imageMap.idImg[0].key,
            licenseImg: this.state.imageMap.licenseImg[0] && this.state.imageMap.licenseImg[0].key,
            doorImg: this.state.imageMap.doorImg[0] && this.state.imageMap.doorImg[0].key,
          };
          dispatch({
            type: 'channel/setChannelValue',
            payload,
          });
          dispatch(routerRedux.push(`/channel/channel-form/credits`));
        } else {
          message.warning('请先填写信息');
        }
      }
    });
  };

  handleBranchIdList = value => {
    this.setState({
      branchIdList: value,
    });
  };

  renderTreeNodesChildren = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode value={item.id} title={item.orgName} key={item.id} dataRef={item}>
            {this.renderTreeNodesChildren(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.id} key={item.id} dataRef={item} title={item.orgName} />;
    });
  };

  handleSelectCustomerClick = () => {
    this.setState({
      dealerLevel: true,
    });
  };

  handleCancelDealerLevel = () => {
    this.setState({
      dealerLevel: false,
    });
  };

  handleAttachmentUploadChange = (info, fieldName) => {
    const fileList = wrapFileList(info);
    const attachmentMap = { ...this.state.attachmentMap };
    attachmentMap[fieldName] = fileList;
    this.setState({
      attachmentMap,
    });
    // console.log('saveFormRef attachmentMap', this.state.attachmentMap);
  };

  saveFormRef = formRef => {
    // console.log('saveFormRef formRef', formRef);
    this.formRef = formRef;
  };

  render() {
    // const { channel: { channelDetailValue } } = this.props;
    const { type, channelDetailValue } = this.state;
    const { system: { allBranchTreeList } } = this.props;

    const { getFieldDecorator, getFieldValue, validateFieldsAndScroll } = this.props.form;

    const defaultAttachmentUploadProps = {
      name: 'file',
      action: solo.uploadImg,
      multiple: true,
      headers: {
        authorization: 'authorization-text',
      },
    };

    const agreementFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.agreement,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'agreement');
      },
    };

    const otherFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.other,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'other');
      },
    };

    return (
      <Row>
        {/* {JSON.stringify(this.state.attachmentMap)} */}
        {this.state.isLoaded && (
          <Form className={styles.stepForm}>
            <div>
              <Row style={{ textAlign: 'centent' }}>
                <Col span={12}>
                  <FormItem label="经销商名称" {...formItemLayout}>
                    {getFieldDecorator('dealerName', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.dealerName : null,
                      rules: [
                        {
                          required: true,
                          message: '请输入经销商名称',
                        },
                      ],
                    })(<Input placeholder="请输入经销商名称" />)}
                  </FormItem>
                </Col>
                <Col span={10}>
                  <FormItem label="经销商等级" {...formItemLayout1}>
                    {getFieldDecorator('rank', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.rank : null,
                    })(
                      <Select>
                        <Option value={1}>A</Option>
                        <Option value={2}>B</Option>
                        <Option value={3}>C</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={2}>
                  <Tooltip title="查看等级说明">
                    <Button
                      onClick={this.handleSelectCustomerClick}
                      style={{ marginTop: '5px' }}
                      type="dashed"
                      size="small"
                      shape="circle"
                      icon="info-circle"
                    />
                  </Tooltip>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="经销商简称" {...formItemLayout}>
                    {getFieldDecorator('simpleName', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.simpleName : null,
                    })(<Input placeholder="请输入经销商简称" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="所属组织" {...formItemLayout}>
                    {getFieldDecorator('branchId', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.branchId : null,
                      rules: [
                        {
                          required: true,
                          message: '请选择所属组织',
                        },
                      ],
                    })(
                      <TreeSelect
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择"
                        allowClear
                        treeDefaultExpandAll
                        onChange={this.handleBranchIdList}
                      >
                        {allBranchTreeList && this.renderTreeNodesChildren(allBranchTreeList)}
                      </TreeSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="负责人" {...formItemLayout}>
                    {getFieldDecorator('leader', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.leader : null,
                    })(<Input placeholder="请输入负责人" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="联系电话" {...formItemLayout}>
                    {getFieldDecorator('phone', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.phone : null,
                    })(<Input placeholder="请输入联系电话" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="垫资账户" {...formItemLayout}>
                    {getFieldDecorator('fundAccount', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.fundAccount : null,
                    })(<Input placeholder="请输入垫资账户" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="开户银行" {...formItemLayout}>
                    {getFieldDecorator('depositBank', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.depositBank : null,
                    })(<Input placeholder="请输入开户银行" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="银行账户" {...formItemLayout}>
                    {getFieldDecorator('bankAccount', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.bankAccount : null,
                    })(<Input placeholder="请输入银行账户" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="营业执照号" {...formItemLayout}>
                    {getFieldDecorator('licenseNo', {
                      initialValue:
                        type == 2 ? channelDetailValue && channelDetailValue.licenseNo : null,
                    })(<Input placeholder="请输入营业执照号" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <FormItem label="照片上传" {...formItemLayout2}>
                    <Col span={4}>
                      {/* {getFieldDecorator('licenseImg', {})( */}
                      <ImageUploader
                        fieldName="营业执照"
                        label="营业执照"
                        key={1}
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '', //附件种类
                          type: '营业执照', //图片类型
                        }}
                        fileList={this.state.imageMap.licenseImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                      {/* )} */}
                    </Col>
                    <Col span={4}>
                      {/* {getFieldDecorator('idImg', {})( */}
                      <ImageUploader
                        fieldName="身份证照"
                        label="身份证照"
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '', //附件种类
                          type: '身份证照', //图片类型
                        }}
                        fileList={this.state.imageMap.idImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                      {/* )} */}
                    </Col>
                    <Col span={4}>
                      <ImageUploader
                        label="门头照"
                        fieldName="门头照"
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        // fileList={this.state.fileList.doorImg}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '', //附件种类
                          type: '门头照', //图片类型
                        }}
                        fileList={this.state.imageMap.doorImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                    </Col>
                    <Col span={4}>
                      {/* {getFieldDecorator('hallImg', {})( */}
                      <ImageUploader
                        label="展厅照"
                        fieldName="展厅照"
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '', //附件种类
                          type: '展厅照', //图片类型
                        }}
                        fileList={this.state.imageMap.hallImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                      {/* )} */}
                    </Col>
                    <Col span={4}>
                      {/* {getFieldDecorator('cardImg', {})( */}
                      <ImageUploader
                        label="名片"
                        fieldName="名片"
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频; 2:OCR识别
                          attachKind: '', //附件种类
                          type: '名片', //图片类型
                        }}
                        fileList={this.state.imageMap.cardImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                      {/* )} */}
                    </Col>
                    <Col span={4}>
                      {/* {getFieldDecorator('bankCardImg', {})( */}
                      <ImageUploader
                        label="银行卡"
                        fieldName="银行卡"
                        maxCount={1}
                        size="large"
                        showRemoveIconType={true}
                        attachmentData={{
                          projectId: '', //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '', //附件种类
                          type: '银行卡', //图片类型
                        }}
                        fileList={this.state.imageMap.bankCardImg}
                        onImageUploaded={this.handleImageUploaded}
                      />
                      {/* )} */}
                    </Col>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="合作协议" {...formItemLayout}>
                    <Upload {...agreementFileUploadProps}>
                      <Button icon="upload">上传文件</Button>
                      <div style={{ lineHeight: '40px', color: '#999999' }}>
                        支持扩展名 .zip .doc .docx .pdf .jpg .png
                      </div>
                    </Upload>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="其他附件" {...formItemLayout}>
                    <Upload {...otherFileUploadProps}>
                      <Button icon="upload">上传文件</Button>
                      <div style={{ lineHeight: '40px', color: '#999999' }}>
                        支持扩展名 .zip .doc .docx .pdf .jpg .png
                      </div>
                    </Upload>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24} style={{ marginLeft: '20%' }}>
                  <FormItem
                    wrapperCol={{
                      xs: { span: 24, offset: 0 },
                      sm: {
                        span: formItemLayout.wrapperCol.span,
                        offset: formItemLayout.labelCol.span,
                      },
                    }}
                    label=""
                  >
                    <Button type="primary" htmlType="submit" onClick={this.handelNextStep}>
                      下一步
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </div>
          </Form>
        )}
        <Modal
          title="等级说明"
          visible={this.state.dealerLevel}
          footer={null}
          keyboard={true}
          onCancel={this.handleCancelDealerLevel}
        >
          <Description />
        </Modal>
      </Row>
    );
  }
}
